package com.wontube.smr.bo.download;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.wontube.smr.bo.pub.ProxyDownloadListener;
import com.wontube.smr.client.model.po.VideoUrl;
import com.wontube.smr.dao.mapper.VideoUrlMapper;
import com.wontube.smr.pub.DefaultDBHelper;




/**
 * @author yuechao
 *
 */
public class VideoDownloadServlet extends HttpServlet {
	private static final long serialVersionUID = -6461237549356667499L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		if (id == null || "".equals(id)) {
			return;
		}

		String title = req.getParameter("title");
		if (title == null || "".equals(title)) {
			return;
		}
		
		VideoUrl videoUrl;
		SqlSession session = DefaultDBHelper.getSqlSession(false);
		try {
			VideoUrlMapper mapper = session.getMapper(VideoUrlMapper.class);
			videoUrl = mapper.selectByPrimaryKey(id);
			if (videoUrl == null) {
				return;
			}
		} finally {
			session.close();
		}
		
	    AsyncContext ac = req.startAsync();
	    ac.setTimeout(24 * 60 * 60 * 1000); // 限一天下载完成
	    ac.start(new ProxyDownloadListener(ac, title, videoUrl.getUrl()));
	}
}
